<?php
/**
 * Connects to database or redirects to install
 * @return resource database link identifier 
 */

/**
 * Common function to use with database
 */
class DB {
    private static $connected = false;
    
    public static function connect() {
        $error = false;
        /* Searching for seetings */
        $settingsFile = 'settings.php';
        if (!file_exists($settingsFile) && file_exists('../settings.php')) {
            $settingsFile = '../settings.php';
        } elseif (file_exists('../../../settings.php')) {
            $settingsFile = '../../../settings.php';
        }
        if(!file_exists($settingsFile)) {
            $error = "Faila nerandamas";
        }
        
        /* Connetcting to database */
        if (!$error) {
            $settings = include $settingsFile;
            $handle = @mysql_connect($settings['DB_HOST'], $settings['DB_USER'], $settings['DB_PASSWORD']);
            if($handle == false) {
                $error = "Faila nerandamas";
            }
        }
        if (!$error) {
            @mysql_query("SET NAMES utf8");
            @mysql_query("SET CHARACTER SET utf8");
            @mysql_query("SET CHARACTER_SET_SERVER = utf8");
            @mysql_query("SET CHARACTER_SET_CONNECTION = utf8");
            @mysql_query("SET CHARACTER_SET_DATABASE = utf8"); 
            $db = @mysql_select_db($settings['DB_DATABASE']);
            $error = ($db == false);
        }
        if ($error) {
            header('Location: install.php');
            exit('<a href="Init/install.php">Idiegti sistema</a>');
        }
        self::$connected = !$error;
        return $error;
    }
    
    /**
     * Executes mysql query.
     */
    public static function query($sql) {
        $result = mysql_query($sql);
        if ($result === false) {
            $nr = mysql_errno();
            $message = mysql_error();
            trigger_error("Error in sql query: $nr: $message \nSQL:\n$sql", E_USER_WARNING);
        }
        return $result;
    }
    
    /**
     * @return array numeric array of fields
     */
    public static function row($sql_result) {
        return mysql_fetch_row($sql_result);
    }
    
    public static function close() {
        if (self::$connected) {
            mysql_close();
            self::$connected = false;
        }
    }
}
